/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.web.controller.commons.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.pay.service.entity.PayLog;
import net.guerlab.smart.pay.web.alipay.AbstractAlipayRequestController;
import net.guerlab.smart.pay.web.alipay.AlipayTradeType;
import net.guerlab.smart.pay.web.controller.commons.notify.alipay.AlipayPageChannelNotifyController;
import net.guerlab.web.result.Succeed;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 支付请求-支付宝-page
 *
 * @author guer
 */
@Tag(name = "支付请求-支付宝-page")
@RestController(AlipayPagePayController.URL)
@RequestMapping(AlipayPagePayController.URL)
public class AlipayPagePayController extends AbstractAlipayRequestController {

    public static final String URL = "/commons/pay/alipay/page";

    @Override
    protected Object pay0(String appId, PayLog payLog, String returnUrl, HttpServletRequest request) {
        AlipayTradePagePayModel bizModel = new AlipayTradePagePayModel();
        bizModel.setOutTradeNo(String.valueOf(payLog.getPayLogId()));
        bizModel.setProductCode("FAST_INSTANT_TRADE_PAY");
        bizModel.setTotalAmount(payLog.getAmount().toString());
        bizModel.setSubject(payLog.getOrderTitle());

        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
        fillRequestData(appId, returnUrl, payRequest, bizModel);
        try {
            return new Succeed<>(Succeed.MSG, buildAlipayClient(appId, true).pageExecute(payRequest).getBody());
        } catch (AlipayApiException e) {
            throw new ApplicationException(e.getErrCode() + ":" + e.getErrMsg());
        }
    }

    @Override
    protected String getNotifyUrl(String appId) {
        return AlipayPageChannelNotifyController.URL + "/" + appId;
    }

    @Override
    protected AlipayTradeType getAlipayTradeType() {
        return AlipayTradeType.PAGE;
    }
}
